// 获取编辑问卷/新建问卷 === 公共逻辑
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { getQuestionService } from "../services/question";
import { useRequest } from "ahooks";
import { UseDispatch, useDispatch } from "react-redux";
import { resetComponents } from "../store/ComponentsReducer";

export function useLoadQuestionData(){
    const { id = ''}= useParams()
    const [loading ,setLoading] = useState(true)
    const [questionData , setQuestionData] = useState({})

    useEffect(() => {
       async function fun(){
        let data = await getQuestionService(id)
        setLoading(false)
        setQuestionData(questionData)
       }
       fun()
    } , [])

    // 自定义hook一定注意要有返回值，不然外层用啥呀
    return {loading , questionData}
}

// 使用useRequest第三方hook封装 useRequest（第一个参数一定是一个异步的方法）
export function useLoadQuestionData_useRequset(){
    const {id  = ''} = useParams()
    async function load(){
        const data = await getQuestionService(id)
        return data
    }
    const {loading , data , error } = useRequest(load)
    return {loading , data , error}
}

export function useLoadQuestionComponentsData(){
    const dispath = useDispatch()
    const {id=''} = useParams() // 根据路径获取文件id
    const {data ,loading ,error, run} = useRequest(
        async (id : string) => {
        if(!id) throw new Error('没有问卷 id')
        const data = await getQuestionService(id)
        return  data
    },{
        manual : true , // 手动调用加载
    })
    // 根据 data 设置 redux store
    useEffect(() => {
        if(!data) return
        const {title = '' , componentsList = []} = data
        // 把 componentsList 存储到redux store中
        dispath(resetComponents({componentsList}))
    } , [data])

    //根据ID 变化，加载ajax请求，获取问卷数据
    useEffect(() => {
        run(id)
    } ,[id]) 

    return {loading , error}
}